/*
 * Created on 31.10.2003
 * Local Projects Database
 * (c) 2003 by eRomania Gateway Association
 */
package ro.gateway.aida.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import ro.gateway.aida.db.PersistenceManager;
import ro.gateway.aida.db.PersistenceToken;



/**
 * @author Mihai Postelnicu
 * e-mail: mihai@ro-gateway.org
 * Implements pagination token
 * shows items from a List, between start and end.
 */
public class PageToken
{
      protected HashMap params;
      protected int no;

      public PageToken( int start, int end, int no )
      {
            params = new HashMap();
            params.put( "start", new Integer( start ) );
            params.put( "end", new Integer( end ) );
            this.no = no;

      }

      public static void tokenizeList(HttpServletRequest request, ServletContext sc, List l, String tokenName) {
      	PersistenceToken token = PersistenceManager.tokenLookup( sc );
      	List pagetk = makePageTokens(l, token);
        request.setAttribute(tokenName,
            PageToken.handleCurrent(request, sc, l));
        request.setAttribute("pagetk", pagetk);
      }
      
      public static List handleCurrent( HttpServletRequest request, ServletContext sc, List l )
      {
            String s_start = request.getParameter( "start" );
            String s_end = request.getParameter( "end" );
            PersistenceToken token = PersistenceManager.tokenLookup( sc );
            int len = Integer.parseInt( Utils.getProperty( token, "listSize" ) );
            if ( l == null || len > l.size() ) return l;
            if ( s_start == null || s_end == null ) return l.subList( 0, len );
            return l.subList( Integer.parseInt( s_start ), Integer.parseInt( s_end ) );
      }

      public static List makePageTokens( List l, PersistenceToken token )
      {
            ArrayList ret = new ArrayList();
            int len = Integer.parseInt( Utils.getProperty( token, "listSize" ) );
            if ( l == null || l.size() <= len ) return null;
            for ( int i = 0; i <= l.size() / len; i++ )
            {
                  ret.add( new PageToken( i * len, ( i + 1 ) * len > l.size() ? l.size() : ( i + 1 ) * len, i + 1 ) );

            }
            return ret;
      }


      /**
       * @return
       */
      public HashMap getParams()
      {
            return params;
      }

      /**
       * @param map
       */
      public void setParams( HashMap map )
      {
            params = map;
      }

      /**
       * @return
       */
      public int getNo()
      {
            return no;
      }

      /**
       * @param i
       */
      public void setNo( int i )
      {
            no = i;
      }

}
